package cn.ckx.coding.common.aspect;

import cn.ckx.coding.common.annotation.log.SysLog;
import cn.ckx.coding.common.utils.http.HttpContextUtils;
import cn.ckx.coding.common.utils.http.IpUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Objects;

/**
 * @ClassName SysLogAspect
 * @Description 系统日志aop
 * @Author kunxin.cai
 * @Date 2021/2/24
 * @Version 1.0
 **/
@Aspect
@Component
@Slf4j
public class SysLogAspect {

    @Pointcut("@annotation(cn.ckx.coding.common.annotation.log.SysLog)")
    public void pointForLog() {
        
    }
    
    @AfterReturning(pointcut = "pointForLog()", returning = "result")
    public void afterReturning(JoinPoint joinPoint, Object result){
        //类名
        String className = joinPoint.getTarget().getClass().getName();
        
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        //方法名
        String name = method.getName();
        SysLog annotation = method.getAnnotation(SysLog.class);
        //入参
        Object[] args = joinPoint.getArgs();
        //请求路径
        String ipAddress = HttpContextUtils.getHttpServletRequest().getRequestURI();
        String resultJson = "";
        try {
            resultJson = new ObjectMapper().writeValueAsString(result);
        } catch (JsonProcessingException e) {
            resultJson = "json转化异常";
        }

        log.info("系统日志输出，请求路径: {}， 类：{}，方法名：{}，方法说明：{}，入参：{}，返回结果: {}" ,
                ipAddress, className, name, annotation.note(), args, resultJson);

    }
    
}
